<template>
  <div class="employee-role-container base-page-container">
    <el-container style="height: 100%;">
      <!-- <el-aside width="179px" style="height: 100%;display: flex;flex-direction: column;">
        <div class="nav">
          <div class="title-box">角色分类</div>
          <el-input v-model="typeSearch" placeholder="分类查询"/>
        </div>
        <div class="tree-box">
          <el-tree
              :data="departmentTree"
              :props="defaultProps"
              @node-click="handleNodeClick"
          />
        </div>
      </el-aside> -->
      <el-main style="height: 100%;display: flex;flex-direction: column;">
        <!-- 搜索区域 -->
        <!-- <common-search
            v-model="searchForm"
            :search-items="searchItemsConfig"
            @search="handleSearch"
            @reset="fetchTableData"
        /> -->

        <!-- 操作按钮区域 -->
        <!-- <action-buttons
            :buttons="{
              add: { visible: true, order: 1, type: 'success' },
              delete: { visible: true, order: 2 }
            }"
            :selected-data="selectedRows"
            :need-select-buttons="['delete']"
            :no-confirm-buttons="['clear-search']"
            @add="handleGoDetail(null, 'add')"
            @delete="handleDelete"
            @clear-search="clearSearch"
        /> -->
        <el-card style="margin-top: 16px;">
          <template #header>
            <div style="display:flex;align-items:center;gap:8px;">
              <span>仓库列表</span>
              <el-button size="small" type="primary" @click="handleWarehouseAdd">新增</el-button>
              <el-button size="small" @click="fetchWarehouses" :loading="warehouseLoading">刷新</el-button>
            </div>
          </template>
          <el-table :data="warehouseList" v-loading="warehouseLoading" style="width: 100%">
            <el-table-column prop="name" label="名称" min-width="160" />
            <el-table-column prop="address" label="地址" min-width="240" />
            <el-table-column prop="phone" label="电话" min-width="140" />
            <el-table-column prop="email" label="邮箱" min-width="200" />
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-button type="primary" link size="small" @click="handleWarehouseEdit(row)">编辑</el-button>
                <el-divider direction="vertical" />
                <el-button type="danger" link size="small" @click="handleWarehouseDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <!-- 表格区域 -->
     

        <!-- 仓库列表（来自 /api/v1/warehouses） -->
     
      </el-main>


    </el-container>
    
    <!-- 仓库编辑弹窗 -->
    <el-dialog
        v-model="warehouseDialogVisible"
        :title="warehouseDialogTitle"
        width="600px"
        destroy-on-close
        @close="resetWarehouseForm"
    >
      <el-form
        ref="warehouseFormRef"
        :model="warehouseForm"
        :rules="warehouseFormRules"
        label-width="90px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="warehouseForm.name" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="warehouseForm.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="warehouseForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="warehouseForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="warehouseDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="warehouseSaving" @click="handleWarehouseSave">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 表单弹窗 -->
    <el-dialog
        v-model="formDialogVisible"
        :title="formTitle"
        width="800px"
        destroy-on-close
        @close="resetForm"
        class="employee-form-dialog"
    >
      <el-form
		style="margin-top: 20px;"
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="detail-form"
        :disabled="formMode === 'view'"
      >
        <div class="form-row">
          <el-form-item label="工号" prop="workNo">
            <el-input v-model="formData.workNo" placeholder="请输入工号" />
          </el-form-item>
          
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名" />
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="所属部门" prop="department">
            <el-select v-model="formData.department" placeholder="请选择部门" style="width: 100%">
              <el-option label="A部门" value="A部门" />
              <el-option label="B部门" value="B部门" />
              <el-option label="C部门" value="C部门" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="所属公司" prop="company">
            <el-select v-model="formData.company" placeholder="请选择所属公司" style="width: 100%">
              <el-option label="公司A" value="公司A" />
              <el-option label="公司B" value="公司B" />
            </el-select>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入手机号" />
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入邮箱" />
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="角色" prop="role">
            <el-select v-model="formData.role" placeholder="请选择角色" style="width: 100%">
              <el-option label="系统管理员" value="系统管理员" />
              <el-option label="技术员" value="技术员" />
              <el-option label="操作员" value="操作员" />
            </el-select>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="是否允许登录" prop="allowLogin">
            <el-radio-group v-model="formData.allowLogin">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="是否启用" prop="isEnable">
            <el-radio-group v-model="formData.isEnable">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="备注" prop="remark" class="full-width">
            <el-input 
              v-model="formData.remark" 
              type="textarea" 
              :rows="4"
              placeholder="请输入备注" 
            />
          </el-form-item>
        </div>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" v-if="formMode !== 'view'">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed} from 'vue'
import {useTheme} from '@/hooks/useTheme'
import {useRouter} from "vue-router";
import { ElMessage, ElMessageBox } from 'element-plus'

// 使用主题组合API
const {themeType} = useTheme()
const router = useRouter()

// 表单相关数据
const formDialogVisible = ref(false)
const formRef = ref(null)
const formMode = ref('add')
const formTitle = computed(() => {
  const titles = {
    add: '新增员工信息',
    edit: '编辑员工',
    view: '查看员工'
  }
  return titles[formMode.value] || '员工信息'
})

// 表单数据
const formData = reactive({
  id: '',
  workNo: '',
  username: '',
  mobile: '',
  company: '',
  department: '',
  role: '',
  isEnable: true,
  allowLogin: true,
  email: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  workNo: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  company: [
    { required: true, message: '请选择所属公司', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' }
  ]
}

// 权限数据
const permissionData = [
  {
    id: 1,
    label: '系统设置',
    children: [
      { id: 11, label: '用户管理' },
      { id: 12, label: '角色管理' },
      { id: 13, label: '权限管理' }
    ]
  },
  {
    id: 2,
    label: '仓库管理',
    children: [
      { id: 21, label: '入库管理' },
      { id: 22, label: '出库管理' },
      { id: 23, label: '库存查询' }
    ]
  },
  {
    id: 3,
    label: '报表管理',
    children: [
      { id: 31, label: '入库报表' },
      { id: 32, label: '出库报表' },
      { id: 33, label: '库存报表' }
    ]
  }
]

// 搜索项配置列表
const searchItemsConfig = [
  {
    label: '工号',
    prop: 'workNo',
    type: 'el-input',
    placeholder: '请输入工号',
    defaultVisible: true
  },
  {
    label: '用户名',
    prop: 'username',
    type: 'el-input',
    placeholder: '请输入用户名',
    defaultVisible: true
  },
  {
    label: '手机号',
    prop: 'mobile',
    type: 'el-input',
    placeholder: '请输入手机号',
    defaultVisible: true
  },
  {
    label: '所属公司',
    prop: 'company',
    type: 'el-select',
    placeholder: '请选择所属公司',
    defaultVisible: true,
    options: [
      {label: '请选择所属公司', value: ''},
      {label: '公司A', value: '公司A'},
      {label: '公司B', value: '公司B'}
    ]
  }
]

// 搜索表单数据
const searchForm = reactive({
  workNo: '',
  username: '',
  mobile: '',
  company: '',
  department: '' // 从树形控件选择
})

// 清空搜索条件
const clearSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchTableData()
}

// 查询操作
const handleSearch = () => {
  pagination.currentPage = 1
  fetchTableData()
}

// 表格加载状态
const tableLoading = ref(false)

// 表格数据
const tableData = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
})

// 分页大小变更事件
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchTableData()
}

// 页码变更事件
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchTableData()
}

// 获取表格数据
const fetchTableData = () => {
  tableLoading.value = true

  // 构造查询参数
  const params = {
    page: pagination.currentPage,
    pageSize: pagination.pageSize,
    ...searchForm
  }

  console.log('查询参数:', params)

  // 这里应该调用接口获取数据
  // 示例使用模拟数据
  setTimeout(() => {
    // 生成演示数据
    tableData.value = Array.from({length: pagination.pageSize}).map((_, index) => ({
      id: index + 1 + (pagination.currentPage - 1) * pagination.pageSize,
      workNo: `工号${10000 + index}`,
      username: `小${String.fromCharCode(65 + index % 26)}`,
      mobile: `155${String(5566000 + index).padStart(5, '0')}`,
      email: `user${index}@example.com`,
      company: index % 2 === 0 ? '公司A' : '公司B',
      department: index % 3 === 0 ? 'A部门' : index % 3 === 1 ? 'B部门' : 'C部门',
      role: index % 3 === 0 ? '系统管理员' : index % 3 === 1 ? '技术员' : '操作员',
      isEnable: index % 3 !== 2,
      allowLogin: index % 2 === 0,
      operateTime: '2024-01-01 08:00:00',
      operator: '小李',
      remark: index % 2 ? '重要人员' : ''
    }))

    tableLoading.value = false
  }, 300)
}

// 选中的行数据
const selectedRows = ref([])

// 表格多选事件
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 编辑/详情按钮事件
const handleGoDetail = (row, type) => {
  formMode.value = type
  resetForm()
  
  if (type === 'add') {
    formDialogVisible.value = true
  } else {
    fetchFormDetail(row.id)
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  Object.assign(formData, {
    id: '',
    workNo: '',
    username: '',
    mobile: '',
    company: '',
    department: '',
    role: '',
    isEnable: true,
    allowLogin: true,
    email: '',
    remark: ''
  })
}

// 获取表单详情数据
const fetchFormDetail = async (id) => {
  try {
    // 这里应该调用接口获取详情
    // 示例使用模拟数据
    tableLoading.value = true
    setTimeout(() => {
      // 通过ID查找对应行数据
      const row = tableData.value.find(item => item.id === id) || {
        id,
        workNo: `工号${id}`,
        username: `小${id}`,
        mobile: `15566009999`,
        email: `user${id}@example.com`,
        company: '公司A',
        department: 'A部门',
        role: '系统管理员',
        isEnable: true,
        allowLogin: true,
        remark: ''
      }
      
      // 更新表单数据
      Object.assign(formData, {
        id: row.id,
        workNo: row.workNo,
        username: row.username,
        mobile: row.mobile,
        email: row.email,
        company: row.company,
        department: row.department,
        role: row.role,
        isEnable: row.isEnable,
        allowLogin: row.allowLogin,
        remark: row.remark
      })
      
      formDialogVisible.value = true
      tableLoading.value = false
    }, 300)
  } catch (error) {
    console.error('获取详情失败', error)
    ElMessage.error('获取详情数据失败')
    tableLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (formMode.value === 'view') {
    formDialogVisible.value = false
    return
  }
  
  try {
    // 表单验证
    await formRef.value.validate()
    
    
  } catch (error) {
    console.error('提交失败', error)
  }
}

// 表格操作权限 - 默认权限设置
const tablePermissions = reactive({
  edit: true,
  view: true
})

// 表格列配置
const tableColumns = [
  {prop: 'workNo', label: '工号', width: 120, minWidth: '120', visible: true},
  {prop: 'username', label: '用户名', width: 120, minWidth: '120', visible: true},
  {prop: 'department', label: '所属部门', width: 120, minWidth: '120', visible: true},
  {prop: 'company', label: '所属公司', width: 120, minWidth: '120', visible: true},
  {prop: 'mobile', label: '手机号', width: 120, minWidth: '120', visible: true},
  {prop: 'email', label: '邮箱', width: 150, minWidth: '150', visible: true},
  {prop: 'role', label: '角色', width: 120, minWidth: '120', visible: true},
  {prop: 'isEnable', label: '启用', width: 80, minWidth: '80', visible: true, slotName: 'is-enable'},
  {prop: 'allowLogin', label: '允许登录', width: 80, minWidth: '80', visible: true, slotName: 'allow-login'},
  {prop: 'operateTime', label: '操作时间', width: 150, minWidth: '150', visible: true},
  {prop: 'operator', label: '操作人', width: 100, minWidth: '100', visible: true},
  {prop: 'operation', label: '操作', width: '160', minWidth: '160', fixed: 'right', visible: true}
]

// 部门查询
const typeSearch = ref('')

// 部门树数据
const departmentTree = [
  {
    label: 'A部门',
    children: [
      {
        label: 'A-1部门',
      },
      {
        label: 'A-2部门',
      }
    ],
  },
  {
    label: 'B部门',
    children: [
      {
        label: 'B-1部门',
      },
      {
        label: 'B-2部门',
      }
    ],
  },
  {
    label: 'C部门',
    children: [
      {
        label: 'C-1部门',
      },
      {
        label: 'C-2部门',
      }
    ],
  }
]

const defaultProps = {
  children: 'children',
  label: 'label',
}

const handleNodeClick = (data) => {
  console.log(data)
  // 选中部门后，设置查询条件中的部门值
  searchForm.department = data.label
  fetchTableData()
}

// 页面初始化
onMounted(async () => {
  fetchTableData()
  fetchWarehouses()
})

// 删除按钮事件
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个员工')
    return
  }

  ElMessageBox.confirm('确定要删除选中的员工吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用接口删除数据
    setTimeout(() => {
      ElMessage.success('删除成功')
      fetchTableData()
    }, 300)
  }).catch(() => {})
}

// =====================================
// 仓库列表：GET /api/v1/warehouses
// 参数：query, skip=0, limit=100
// 渲染字段：name, address, phone, email
// =====================================
const warehouseList = ref([])
const warehouseLoading = ref(false)

const fetchWarehouses = async () => {
  try {
    warehouseLoading.value = true
    // 这里使用相对路径，确保可被本地代理或服务器转发
    const url = `/api/v1/warehouses?query=&skip=0&limit=100`
    const res = await fetch(url, {
      method: 'GET'
    })
    if (!res.ok) {
      throw new Error(`请求失败: ${res.status}`)
    }
    const data = await res.json()
    // 期望 data 为数组
    warehouseList.value = Array.isArray(data) ? data : []
  } catch (err) {
    console.error('获取仓库列表失败', err)
    ElMessage.error('获取仓库列表失败')
  } finally {
    warehouseLoading.value = false
  }
}

// 仓库编辑逻辑
const warehouseDialogVisible = ref(false)
const warehouseFormRef = ref(null)
const warehouseSaving = ref(false)
const warehouseMode = ref('edit') // 'add' | 'edit'
const warehouseDialogTitle = computed(() => warehouseMode.value === 'add' ? '新增仓库' : '编辑仓库')
const warehouseForm = reactive({
  // 尽量保留后端返回的字段，提交当前行数据
  id: '',
  name: '',
  address: '',
  phone: '',
  email: ''
})

const warehouseFormRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
}

const resetWarehouseForm = () => {
  if (warehouseFormRef.value) {
    warehouseFormRef.value.resetFields()
  }
  Object.assign(warehouseForm, {
    id: '',
    name: '',
    address: '',
    phone: '',
    email: ''
  })
}

const handleWarehouseAdd = () => {
  warehouseMode.value = 'add'
  resetWarehouseForm()
  warehouseDialogVisible.value = true
}

const handleWarehouseEdit = (row) => {
  // 回显当前行数据
  warehouseMode.value = 'edit'
  resetWarehouseForm()
  Object.assign(warehouseForm, row)
  warehouseDialogVisible.value = true
}

const handleWarehouseSave = async () => {
  try {
    await warehouseFormRef.value.validate()
  } catch (e) {
    return
  }

  try {
    warehouseSaving.value = true
    const payload = {
      name: warehouseForm.name,
      address: warehouseForm.address,
      phone: warehouseForm.phone,
      email: warehouseForm.email
    }
    const isAdd = warehouseMode.value === 'add'
    const url = isAdd ? `/api/v1/warehouses` : `/api/v1/warehouses/${encodeURIComponent(warehouseForm.id)}`
    const method = isAdd ? 'POST' : 'PUT'
    if (!isAdd && !warehouseForm.id && warehouseForm.id !== 0) {
      ElMessage.error('缺少仓库ID，无法保存')
      return
    }
    const res = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload)
    })
    if (!res.ok) {
      throw new Error(`保存失败: ${res.status}`)
    }
    ElMessage.success('保存成功')
    warehouseDialogVisible.value = false
    fetchWarehouses()
  } catch (err) {
    console.error('保存仓库失败', err)
    ElMessage.error('保存失败')
  } finally {
    warehouseSaving.value = false
  }
}

const handleWarehouseDelete = (row) => {
  if (!row || (!row.id && row.id !== 0)) {
    ElMessage.error('缺少仓库ID，无法删除')
    return
  }
  ElMessageBox.confirm('确定要删除该仓库吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await fetch(`/api/v1/warehouses/${encodeURIComponent(row.id)}`, {
        method: 'DELETE'
      })
      if (!res.ok) {
        throw new Error(`删除失败: ${res.status}`)
      }
      ElMessage.success('删除成功')
      fetchWarehouses()
    } catch (err) {
      console.error('删除仓库失败', err)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}
</script>

<style lang="scss" scoped>
/* 使用全局样式类，保留特殊样式覆盖 */
.employee-role-container {
  padding-left: 0;
  padding-top: 0;
}

.el-aside {
  .nav {
    display: flex;
    flex-direction: column;
    align-items: center;

    .title-box {
      width: 179px;
      height: 42px;
      background: #F0F6FF;
      padding: 10px 20px;
      box-sizing: border-box;
      font-weight: 400;
      font-size: var(--el-font-size-base);
      color: #000000;
    }

    .el-input {
      width: 150px;
      margin: 10px 0;
    }

    :deep(.el-input__wrapper) {
      text-align: center;
      border-radius: 30px;
    }
  }

  .tree-box {
    padding: 0 5px;
    flex: 1;
    overflow: auto;
  }
}

.el-main {
  padding-top: 20px;
  padding-left: 5px;
}

.employee-form-dialog {
  :deep(.el-dialog__header) {
    margin-right: 0;
    text-align: center;
    font-weight: bold;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  :deep(.el-dialog__body) {
    padding: 20px 40px;
  }
  
  :deep(.el-dialog__footer) {
    padding: 10px 0 20px;
    border-top: 1px solid #f0f0f0;
  }
}

.detail-form {
  .form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    
    .el-form-item {
      flex: 1;
      min-width: 0;
      margin-bottom: 0;
    }
    
    .full-width {
      flex: 2;
      width: 100%;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-top: 10px;
}
</style> 